let pageSize=2;
let namearr = [];
let table_div = document.querySelector("#table_div");
let table = document.createElement("table");
table.setAttribute("id", "table")
table_div.appendChild(table); //会覆盖原来的样式 
table.className = "table table-hover table-bordered"; // table.classList
let thead = document.createElement("thead");
table.appendChild(thead);
let tbody = document.createElement("tbody");
table.appendChild(tbody);
let tr = document.createElement("tr");
thead.appendChild(tr);

let titles = ["<input name='cb_select_all' type='checkbox'>","序号", "姓名","性别","电话", "宿舍楼","用户名","操作"];
titles.forEach(function (value, index) {
  let th = document.createElement("th");
  tr.appendChild(th);
  th.innerHTML = value; // th.className = "text-center"; 
  th.classList.add("text-center"); // th.style.css属性 = css属性值，一般不用
});

function dm(id,name,gender,phone,dorm,username) {
  obj = new Object();
  obj.id = id;
  obj.name = name;
  obj.gender=gender;
  obj.phone = phone;
  obj.dorm = dorm;
  obj.username = username;
  return obj;
}
let d1=new dm(1,"柳岩","女","123151251","412栋","柳岩");
let d2=new dm(2,"白百何","女","123112251","411栋","白百何");
let d3=new dm(3,"胡海泉","男","123442251","413栋","胡海泉");
dmlist = [d1,d2,d3];

//更细菜单(重新插入数组中的元素)
function updateTable(array) {
  if (!Array.isArray(array)) {
      throw new Error("array 必须是一个数组");
  }
  array.forEach(function (value, index) {
      namearr.push(value.name);
      tr = document.createElement("tr");
      tr.index = index;
      tr["data-id"] = value.id;
      tbody.appendChild(tr);
      let tds = `
<td><input size=6 id="${value.id}" name="cb_select" type="checkbox"></td>
<td><span>${value.id}</span></td>
<td editable><span>${value.name}</span><input size=6 type="text" name="name"
value="${value.name}" hidden></td>
<td editable>
<span>${value.gender}</span>
<input size=6 type="text" hidden name="gender" value="${value.gender}">
</td>
<td editable>
<span>${value.phone}</span>
<input size=6 type="text" hidden name="phone" value="${value.phone}">
</td>
<td editable>
<span>${value.dorm}</span>
<input size=6 type="text" hidden name="dorm" value="${value.dorm}">
</td>
<td editable>
<span>${value.username}</span>
<input size=6 type="text" hidden name="introduction" value="${value.username}">
</td>
<td>
<button type="button" class="btn btn-info btn-sm" onclick="edit(event)">编辑</button>
<button type="button" class="btn btn-danger btn-sm" onclick="del(event)">删除</button>
</td>
`;
      tr.innerHTML = tds;
  });
  let tds = document.querySelectorAll("tbody tr td");
  // console.log(tds);
  Array.from(tds).forEach(function (value) {
      //不会覆盖原来的样式
      value.classList.add("text-center");
  });
}

updateTable(dmlist);



function insert(event) {
  let addTr = `
<tr>
<td><input type="checkbox"></td>
<td></td>
<td><input size=6 type="text" name="name" placeholder="名称"></td>
<td><input  size=6 type="text" name="gender" placeholder="性别"></td>
<td><input size=6 type="text" name="phone" placeholder="电话"></td>
<td><input  size=6 type="text" name="dorm" placeholder="宿舍楼"></td>
<td><input size=6 type="text" name="username" placeholder="用户名"></td>
<td>
<button type="button" class="btn btn-info btn-sm" onclick="save(event)">保存</button>
<button type="button" class="btn btn-danger btn-sm" onclick="cancel(event)">取消</button>
</td>
</tr>
`;
  table.querySelector("tbody").insertAdjacentHTML("afterend", addTr);
}

function edit(event) {
  let self = event.target;
  let editTr = self.parentNode.parentNode;
  let tds = editTr.querySelectorAll("td[editable]");
  console.log(tds);
  if (self.innerText == "编辑") {
      tds.forEach(value => {
          value.querySelector("span").hidden = true;
          value.querySelector("input").hidden = false;
      });
      self.innerText = "保存";
  } else {
      save(event, newObj => {
          let dataId = editTr["data-id"];
          console.log(`dataId: ${dataId}`);
          let editIndex;
          dmlist.forEach((value, index) => {
              if (value.id == dataId) {
                  editIndex = index;
              }
          });
          let editObj = dmlist[editIndex];
          newObj.id = editObj.id;
          dmlist.splice(editIndex, 1, newObj);
      });
      // self.innerText = "编辑";
  }
}


function save(event, callback) {
  let self = event.target;
  let editTr = self.parentNode.parentNode;
  let inputs = editTr.querySelectorAll("input");
  // let newObj = {
  // name: inputs[1].value,
  // price: input[2].value
  // };
  let newObj = {}; //要保存的数据内容
  inputs.forEach(value => {
      console.log(value);
      if (value.type != "checkbox") {
          if (value.type == "number") {
              newObj[value.name] = value.valueAsNumber;
          } else if (value.type == "date") {
              newObj[value.name] = value.valueAsDate;
          } else {
              newObj[value.name] = value.value;
          }
      }
  });
  if (callback) {
      callback(newObj);
  } else {
      newObj.id = getInsertId(dmlist);
      //保存到数组中
      dmlist.push(newObj);
  }
  //刷新表格
  pagination(dmlist, 1);
}

function add(event) {
  console.log("add");
  let self = event.target;
  let span = self.previousElementSibling;
  // console.log(span);
  let tr = self.parentNode.parentNode;
  let count = parseInt(span.innerText) + 1;
  span.innerText = count;
  dmlist[getIndexById(dmlist, tr["data-id"])].count = count;
  console.log(dmlist);
}
/**
* 根据id从dmlist数组寻找索引
* @param array
* @param id
* @returns {*}
*/
function getIndexById(array, id) {
  let editIndex;
  array.forEach((value, index) => {
      if (value.id == id) {
          editIndex = index;
      }
  });
  return editIndex;
}


function clearTable() {
  Array.from(table.tBodies).forEach(value => {
      while (value.hasChildNodes()) {
          value.firstChild.remove();
      }
  })
}

function getInsertId(array) {
  if (!Array.isArray(array)) {
      throw new Error("array 必须是一个数组");
  }
  let maxId = array[0].id;
  array.forEach(value => {
      if (maxId < value.id) {
          maxId = value.id;
      }
  });
  return maxId + 1;
}

let cb_select_all = document.querySelector("input[name='cb_select_all']");
cb_select_all.onchange = function (event) {
  let self = event.target;
  console.log(self.checked);
  let cb_selects = table.querySelectorAll("input[name='cb_select']");
  cb_selects.forEach((value, index) => {
      value.checked = self.checked;
  });
}


function delBatch(event) {
  let cb_selects = table.querySelectorAll("input[name='cb_select']");
  cb_selects.forEach((value, index) => {
      if (value.checked) {
          // let editTr = value.parentNode.parentNode;
          // delete dmlist[editTr.index];
          let a=confirm("你确定要删除么");
          if(a){
              let id = value.id; //数据的id属性
              dmlist.forEach((item, itemIndex) => {
                  if (item.id == id) {
                      dmlist.splice(itemIndex, 1);
                  }
              });
          }
      }
  });
  //刷新表格
  pagination(dmlist, 1);
}

function del(event) {
  let self = event.target;
  let editTr = self.parentNode.parentNode;
  let result = confirm(`是否删除id为${dmlist[editTr.index].id}的数据`);
  if (result) {
      // editTr.remove();
      // console.log(editTr.index);
      // console.log(editTr["data-id"]);
      dmlist.forEach((value, index) => {
          if (editTr["data-id"] == value.id) {
              dmlist.splice(index, 1);
          }
      });
      // console.log(dmlist);
      //刷新表格
      pagination(dmlist, 1);
  }
}

function search() {
  // event.stopPropagation();//终止事件冒泡
  let form = document.forms[0];
  let input_name;
  function a1(){
      input_name =document.getElementById("namebtnv");
      return input_name;
  }
  let namebox= form["name"].value;
  let filterdmlist = dmlist;


  if (namebox.trim().length > 0) {
      filterdmlist = filterdmlist.filter((value, index, array) => {
          //搜索，精确匹配，模糊匹配
          // if (name.trim() == value.name.trim()) {
          //
          // }
          if (value.name.indexOf(namebox.trim()) != -1) {
              return true;
          }
          return false;
      });
  }
  if (a1()!=null&&input_name.innerText.length > 0) {
      console.log(input_name.innerText);
      filterdmlist = filterdmlist.filter((value, index, array) => {
          if (value.name.indexOf(input_name.innerText) != -1) {
              return true;
          }
          return false;
      });
  }
  //刷新表格
  pagination(filterdmlist, 1);
}

function clear(tag) {
  if (tag instanceof Node) {
      while (tag.hasChildNodes()) {
          tag.firstChild.remove();
      }
  }
}

function cancel(event){
    let self=event.target;
    let editTr = self.parentNode.parentNode;
    editTr.remove(); 
}

function pagination(array, pageNum = 1) {
  if (!Array.isArray(array)) {
      throw new Error("array 必须是一个数组");
  }
  let total = array.length; //数据总数

  let page_total = document.getElementById("page_total");
  page_total.textContent =`一共${total}条记录`;
  let page_select = document.getElementById("page_select");

  page_select.onchange=function(event){
      pageSize=parseInt(page_select.value);
      pagination(array,pageNum);
  }

  let pageCount; //一共有多少页
  if (total % pageSize === 0) {
      pageCount = Math.floor(total / pageSize);
  } else {
      pageCount = Math.floor(total / pageSize) + 1;
  }
  // let pageNum = 0;//当前页码
  let firstNum = 1; //首页码1
  let lastNum = pageCount; //尾页码
  let preNum = pageNum - 1; //上一页页码
  if (preNum <= 1) {
      preNum = 1;
  }
  let nextNum = pageNum + 1; //下一页页码
  if (nextNum >= pageCount) {
      nextNum = pageCount;
  }
  let pagination_ul = document.querySelector(".pagination");
  clear(pagination_ul);
  let pos = "beforeend";
  //首页
  let li;
  li = document.createElement("li");
  li.className = pageNum == firstNum ? "disabled" : "";
  li.innerHTML = `
<a href="javascript:void(0);">
<span>首页</span></a>
`;
  li.onclick = function () {
      pagination(array, firstNum);
  };
  pagination_ul.insertAdjacentElement(pos, li);
  //上一页

  li = document.createElement("li");
  li.className = pageNum == firstNum ? "disabled" : "";
  li.innerHTML = `
<a href="javascript:void(0);">
<span>上一页</span>
</a>
`;
  li.onclick = function () {
      pagination(array, preNum);
  };
  pagination_ul.insertAdjacentElement(pos, li);
  //中间的页码
  for (let i = 1; i <= pageCount; i++) {
      li = document.createElement("li");
      li.className = i == pageNum ? "active" : "";
      li.innerHTML = `
<a href="javascript:void(0);">
<span>${i}</span>
</a>
`;
      li.onclick = function () {
          pagination(array, i);
      };
      pagination_ul.insertAdjacentElement(pos, li);
  }
  //下一页
  li = document.createElement("li");
  li.className = pageNum == lastNum ? "disabled" : "";
  li.innerHTML = `
<a href="javascript:void(0);">
<span>下一页</span>
</a>
`;
  li.onclick = function () {
      pagination(array, nextNum);
  };
  pagination_ul.insertAdjacentElement(pos, li);
  //尾页
  li = document.createElement("li");
  li.className = pageNum == lastNum ? "disabled" : "";
  li.innerHTML = `
<a href="javascript:void(0);">
<span>尾页</span>
</a>
`;
  li.onclick = function () {
      pagination(array, lastNum);
  };
  // li.addEventListener("click", function () {
  // pagination(array, pageCount);
  // });
  pagination_ul.insertAdjacentElement(pos, li);

  clearTable();
  updateTable(array.filter((value, index) => {
      return index < pageSize * pageNum && index >= pageSize * (pageNum - 1);
  }));
}
pagination(dmlist, 1);


let ul = document.createElement("ul");
let ul2 = document.createElement("ul");
//下拉菜单
namearr=namearr.filter(function (value, index) {
  return namearr.indexOf(value) == index;
});
namearr.forEach(function (value, index) {
  let li2 = document.createElement("li");
  let a2 = document.createElement("a");
  let namelist = document.getElementById("namelist");
  let namebtn=document.getElementById("namebtn");
  namelist.appendChild(ul2);
  ul2.classList.add("dropdown-menu");
  ul2.appendChild(li2);
  li2.appendChild(a2);
  a2.setAttribute("href", "#");
  a2.innerText = `${value}`;
  a2.addEventListener('click', function() {
      namebtn.innerHTML=`<span id="namebtnv">${value}</span>  &nbsp <span class="caret"></span>`
    })
})





let tds = document.querySelectorAll("tbody tr td");
Array.from(tds).forEach(function (value) {
  //不会覆盖原来的样式 
  value.classList.add("text-center");
});

function clean() {
  let table1 = document.getElementById("table");
  console.log(table1);
  while (table1.hasChildNodes()) {
    table1.firstChild.remove();
  }
}

            //   //左导航栏识别
            //   let navlist=document.querySelector(".list-group").children;
            //   let iden=sessionStorage.getItem("identify");
            //   Array.from(navlist).forEach(function(value,index){
            //     let attr=value.getAttribute("data-identify");
            //         if(iden=="stu"&&index==0)
            //         {
            //             value.setAttribute("href","stuW.html")
            //         }else if(iden=="dmm"&&index==0)
            //         {
            //             value.setAttribute("href","dMW.html")
            //         }else if(index==0)
            //         {
            //             value.setAttribute("href","sysW.html")
            //         }
            //         if(iden=="stu"&&attr!="all")
            //         {
            //         value.style.display="none";
            //         }
            //         if(iden=="dmm"&&attr=="sys")
            //         {
            //         value.style.display="none";
            //         }
            //   })


            let menusJsonStr = sessionStorage.getItem("menus");
            let menus = JSON.parse(menusJsonStr);
            let identify = sessionStorage.getItem("identify");
            let menusdiv=document.querySelector("#menusdiv");
            if(identify==null)
            {
                window.location="sysW.html"
            }
            menus.forEach(function(value,index){
                let menu_opt=`
                     <a href="${value.href}" class="list-group-item" ${index==0? 'active' :''}>${value.title}</a>
                `;
                menusdiv.insertAdjacentHTML("beforeend",menu_opt);
            });
            